/*
 * Created by SharpDevelop.
 * User: user
 * Date: 12/14/2008
 * Time: 5:00 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using System.Windows.Forms;

namespace csharp.rad.general
{
	/// <summary>
	/// Description of frmRegisterCustomer.
	/// </summary>
	public partial class frmRegisterCustomer : frmRegisterPerson
	{
		private Customer customer = new Customer();
		private Address address2 = new Address();
		private Customers listCustomers = new Customers();
		private Employees listEmployees = new Employees();
		private Visits    listVisits    = new Visits();
		
		public frmRegisterCustomer()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			this.dgvMain.Size = new Size(808, 426);
			
			base.person = customer.person;
		}
		
		#region overrided methods
			protected override void newEvent()
			{
				customer.clear();
				base.newEvent();
			}
			
			protected override bool delete()
			{
				return base.delete();
			}
			
			protected override void fillDataGridView()
			{
				//base.fillDataGridView();
				
				listCustomers.fillList();
				
				int tam = listCustomers.count();
				
				dgvMain.Rows.Clear();
				for (int i=0; i < tam; i++)
					dgvMain.Rows.Add ( new String[] {listCustomers.get(i).id,
					                  				 listCustomers.get(i).person.id,
					                  				 listCustomers.get(i).person.code,
					                  				 listCustomers.get(i).person.name, 
					                  				 listCustomers.get(i).person.cpfCnpj
					                  				 });				
			}
			
			protected override void find()
			{
				base.find();
			}
			
			protected override bool save()
			{
				common.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
				//TODO: Mostrar mensagens para o usuario, quando der erro
				if (!base.save())
				{
					common.Database.RollBack();
					return false;
				}
				
				if (!customer.save())
				{
					common.Database.RollBack();
					return false;
				}
				
				address2.personId = person.id;
				if (!address2.save())
				{
					common.Database.RollBack();
					return false;
				}
				
				//Save visits
				if (!saveVisits())
				{
					common.Database.RollBack();
					return false;
				}
				
				common.Database.Commit();
				return true;
			}
			
			protected override void setClass()
			{
				base.setClass();
				
				//Set Address
				type.get("address","002"); //Comercial

				address2.address 				= txtAddress2Address.Text;
				address2.neighborhoodId 	= (cmbAddress2Neighborhoods.SelectedItem as Neighborhood).id;
				address2.typeId				= type.id;
				address2.complement			= txtAddress2Complement.Text;
				address2.reference			= txtAddress2Reference.Text;
				address2.number				= txtAddress2Number.Text;
				address2.enable				= chkAddress2Enable.Checked;
			}
			
			protected override void setEdits()
			{
				//base.setEdits();
				
				customer.id = dgvMain.CurrentRow.Cells["customerId"].Value.ToString();
				
				if (customer.get())
				{
					base.fillEdits();
					
					//Address					
					type.get("address","002"); //Comercial
	
					if (address2.get(person.id, type.id))
					{
						listNeighborhoods.search(address2.neighborhoodId);
						
						txtAddress2Address.Text		=  address2.address; 
						cmbAddress2Neighborhoods.SelectedIndex=  listNeighborhoods.getIndex();			
						txtAddress2Complement.Text	=  address2.complement; 
						txtAddress2Reference.Text	=  address2.reference; 
						txtAddress2Number.Text		=  address2.number; 
						chkAddress2Enable.Checked	= 	address2.enable;
						txtAddress2ZipCode.Text    = listNeighborhoods.get().zipCode;
					}
					
					listVisits.fillList(customer.id);
					fillDataGridVisits();
				}
			}
			
			protected override bool update()
			{				
				common.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
				//TODO: Mostrar mensagens para o usuario, quando der erro
				if (!base.update())
				{
					common.Database.RollBack();
					return false;
				}
				
				if (!customer.update())
				{
					common.Database.RollBack();
					return false;
				}
				
				//address2.personId = person.id;
				if (!address2.update())
				{
					common.Database.RollBack();
					return false;
				}
				
				//Save visits
				if (!saveVisits())
				{
					common.Database.RollBack();
					return false;
				}
				
				common.Database.Commit();
				return true;				
			}
			
			protected override void init()
			{
				DataGridViewTextBoxColumn customerId = new DataGridViewTextBoxColumn();
				
				customerId.Visible = false;
				customerId.Name    = "customerId";
				dgvMain.Columns.Add(customerId);
				
				base.init();
				
				Functions.fillComboCountries(listCountries, cmbAddress2Country, "id", "name");
				
				Functions.fillComboStates(listStates, cmbAddress2State, "id", "name");
				
				Functions.fillComboCities(listCities, cmbAddress2City, "id", "name");
				
				Functions.fillComboNeighborhoods(listNeighborhoods, cmbAddress2Neighborhoods, "id", "name");
				
				listEmployees.getAssist();
				Functions.fillComboEmployees(listEmployees, cmbAssist, "id", "name");
			}
			
		#endregion
		
		private void TxtAddress2ZipCodeLeave(object sender, EventArgs e)
		{
			if (!txtAddress2ZipCode.Equals(String.Empty))
			{
				if (listNeighborhoods.searchByZipCode(txtAddress2ZipCode.Text))
				{
					String id = listNeighborhoods.get().id;
					String cityId = listNeighborhoods.get().cityId;
					
					listNeighborhoods.fillList(cityId);
					Functions.fillComboNeighborhoods(listNeighborhoods, cmbAddress2Neighborhoods, "id", "name");
					
					Functions.setSelectIndexComboNeighborhoods(cmbAddress2Neighborhoods, id);
				}
			}
		}
		
		private void CmbAddress2CountrySelectedValueChanged(object sender, EventArgs e)
		{
			if ((cmbAddress2Country.SelectedIndex >= 0) && (!mutexCountry))
			{
				cmbAddress2State.SelectedIndex = -1;
				cmbAddress2City.SelectedIndex  = -1;
				cmbAddress2Neighborhoods.SelectedIndex = -1;
				listStates.fillList((cmbAddress2Country.SelectedItem as Country).id);
				Functions.fillComboStates(listStates, cmbAddress2State, "id", "name");
			}	
			mutexCountry= false;
		}
		
		private void CmbAddress2StateSelectedValueChanged(object sender, EventArgs e)
		{
			if (cmbAddress2State.SelectedIndex >= 0)
			{
				if (mutexState)
				{
					mutexCountry= true;
					listStates.search((cmbAddress2State.SelectedItem as State).id);
					Functions.setSelectIndexComboCountries(cmbAddress2Country, listStates.get().countryId);					
					mutexCountry= false;
				}
				else
				{
					cmbAddress2City.SelectedIndex = -1;
					cmbAddress2Neighborhoods.SelectedIndex = -1;
					listCities.fillList((cmbAddress2State.SelectedItem as State).id);
					Functions.fillComboCities(listCities, cmbAddress2City, "id", "name");
				}
			}
			mutexState= false;
		}
		
		private void CmbAddress2CitySelectedValueChanged(object sender, EventArgs e)
		{
			if (cmbAddress2City.SelectedIndex >= 0)
			{
				if (mutexCity)
				{
					mutexState= true;
					listCities.search((cmbAddress2City.SelectedItem as City).id);
					Functions.setSelectIndexComboStates(cmbAddress2State, listCities.get().stateId);
					mutexState= false;
				}
				else
				{
					cmbAddress2Neighborhoods.SelectedIndex= -1;
					listNeighborhoods.fillList((cmbAddress2City.SelectedItem as City).id);
					Functions.fillComboNeighborhoods(listNeighborhoods, cmbAddress2Neighborhoods, "id", "name");
				}
			}
			mutexCity= false;
		}
				
		private void CmbAddress2NeighborhoodsSelectedValueChanged(object sender, EventArgs e)
		{
			if (cmbAddress2Neighborhoods.SelectedIndex >= 0)
			{
				mutexCity= true;
				listNeighborhoods.search((cmbAddress2Neighborhoods.SelectedItem as Neighborhood).id);
				Functions.setSelectIndexComboCities(cmbAddress2City, listNeighborhoods.get().cityId);
				mutexCity = false;
			}
		}
		
		private void BtnAddressMainClick(object sender, EventArgs e)
		{
			cloneAddress();
		}
		
		private void cloneAddress()
		{
			txtAddress2Address.Text			  = txtAddress1Address.Text;
			cmbAddress2Status.SelectedIndex = cmbAddress1Status.SelectedIndex;
			chkAddress2Enable.Checked		  = chkAddress1Enable.Checked;
			txtAddress2Number.Text			  = txtAddress1Number.Text;
			txtAddress2ZipCode.Text			  = txtAddress1ZipCode.Text;
			cmbAddress2Neighborhoods.SelectedIndex = cmbAddress1Neighborhoods.SelectedIndex;
			txtAddress2Reference.Text		  = txtAddress1Reference.Text;
			txtAddress2Complement.Text		  = txtAddress1Complement.Text;
		}
	
		private void fillDataGridVisits()
		{
			int tam = listVisits.count();
			
			dgvVisits.Rows.Clear();
			for (int i=0; i < tam; i++)
				dgvVisits.Rows.Add(new String[] {listVisits.get(i).id, 
				                   					listVisits.get(i).date,
				                   					listVisits.get(i).situation,
				                   					listVisits.get(i).contactType,
				                   });
		}
		
		private void BtnAddVisitClick(object sender, EventArgs e)
		{
			Visit aux 		 = new Visit();
			
			aux.date 		 = dtpVisitDate.Text;
			aux.situation 	 = cmbSituation.Text;
			aux.contactType = cmbContactType.Text;
			aux.employeeId  = (cmbAssist.SelectedItem as common.structCombo).id;
			aux.obs         = txtVisitObs.Text;
			
			listVisits.add(aux);
			fillDataGridVisits();
		}
	
		private bool saveVisits()
		{
			for (int i=0; i < listVisits.count(); i++)
			{
				listVisits.get(i).customerId = customer.id;
				if (!listVisits.get(i).store())
				{
					return false;
				}
			}
			return true;
		}
	}
}
